<template>
  <div>
    <el-tree
      :data="data"
      props="defaultProps"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span @click="info(data.id)">{{ data.name }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => add(data)">
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog title="添加" :visible.sync="editFormVisibleAdd" width="30%" @click="closeDialog">
    <el-form label-width="120px" :model="formInline" :rules="rules" ref="formInline">
      <el-form-item label="商品名称" prop="productName">
        <el-input size="small" v-model="formInline.productName" auto-complete="off" placeholder="请输入商品名称"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="closeDialog">取消</el-button>
      <el-button size="small" type="primary" class="title" @click="submitFormAdd('formInline')">添加</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
export default {
  name: "tree",
  created() {
    this.getData()
  },
  data() {
    return {
      editFormVisibleAdd:false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      formInline: {
        productName:'',
        parent_id:'',
      },
      rules: {
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    //获取分类数据
    async getData(){
      var _this=this;
      await this.axios({
        method:"get",
        url:"http://192.168.1.3:8080/getClassify",
      }).then(function (response){
        _this.data = _this.toTree(response.data)
      });
    },
    //json数据转换为tree
    toTree(data) {
  // 删除所有 children,以防止多次调用
  data.forEach(function(item) {
    delete item.children;
  });

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  var map = {};
  data.forEach(function(item) {
    map[item.id] = item;
  });

  var val = [];
  data.forEach(function(item) {
    // 以当前遍历项的pid,去map对象中找到索引的id
    var parent = map[item.parentId];
    // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item);
    }
  });
  return val;
},
    //添加弹窗
    async add(data) {
      this.editFormVisibleAdd = true
      this.formInline.parent_id=data.id
    },
    //添加分类数据
    submitFormAdd(editData){
      this.$refs[editData].validate(async valid => {
        if (valid) {
          await this.$confirm('确定要添加吗?', '信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            var _this = this;
            await this.axios({
              method: "post",
              url: "http://192.168.1.3:8080/addClassify",
              data: {
                parentId:_this.formInline.parent_id,
                name:_this.formInline.productName,
              },
            }).then(function (response) {
              if(response.data=="Ok"){
                _this.editFormVisibleAdd=false
                _this.$message.success("创建成功")
              }else {
                _this.editFormVisibleAdd=false
                _this.$message.error("创建失败")
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消添加'
            })
          })
          await this.getData();
        } else {
          this.editFormVisibleAdd = false
          this.$message.error('请输入信息')
        }
      })
    },
    //移除分类数据
    async remove(data) {
      await this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var _this = this;
        await this.axios({
          method: "post",
          url: "http://192.168.1.3:8080/deleteClassify",
          data: {
            id: data.id,
          },
        }).then(function (response) {
          if (response.data == "Ok") {
            _this.$message.success("删除成功")
          } else {
            _this.$message.error("删除失败")
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      await this.getData();
    },
    //商品信息
    info(id){
      alert(id)
    },
    //关闭弹窗
    closeDialog() {
      this.editFormVisibleAdd = false
    }
  }
};
</script>

<style scoped>

</style>
